package com.springboot.springboot4.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.springboot4.Bean.User;
import com.springboot.springboot4.Serivce.UserService;
import com.springboot.springboot4.exeception.UserTooManyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName:
 * @author: CKC
 * @DateTime: 2021/1/30 9:44
 */
@Controller
public class TableController {
    
    @Autowired
    UserService userService;
    
    @GetMapping(value = "/dynamic_table")
    public String dynamic_table(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
    
/*        List<User> users = Arrays.asList(new User("张三", "123456"),
                new User("lisi", "ersdsds"),
                new User("haha", "21143"),
                new User("uadgu", "126534"));
        
        model.addAttribute("users", users);
        
        //自定义异常 测试数据
        if (users.size() > 3) {
            throw new UserTooManyException();
        }*/
        
        
        //从数据库中查出user表中的用户进行展示
        List<User> users = userService.list();
        System.out.println(Arrays.asList(users));
        
        //分页查询数据
        Page<User> userPage = new Page<>(pn, 2);
        //分页查询的结果
        Page<User> page = userService.page(userPage, null);
        model.addAttribute("page", page);
        return "table/dynamic_table";
    }
    
    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn", defaultValue = "1") Integer pn,
                             RedirectAttributes ra) {
        
        userService.removeById(id);
        
        ra.addAttribute("pn", pn);
        return "redirect:/dynamic_table";
    }
    
    
    @GetMapping(value = "/basic_table")
    public String basic_table(@RequestParam(value = "a", required = false) int a) {
        int aa = 1 / 0;
        /**异常处理测试行*/
        return "table/basic_table";
    }
    
    @GetMapping(value = "/editable_table")
    public String editable_table() {
        return "table/editable_table";
    }
    
    @GetMapping(value = "/pricing_table")
    public String pricing_table() {
        return "table/pricing_table";
    }
    
    @GetMapping(value = "/responsive_table")
    public String responsive_table() {
        return "table/responsive_table";
    }
}
